import Input from '@/components/Input';
import NavBar from '@/components/NavBar';
import { TextArea } from '@/components/Textarea';
import { useAppSelector } from '@/store';
import {
  getUserProfileAction,
  updatePhotoAction,
  updateProfileAction,
} from '@/store/action/user';
import { ProfileType } from '@/store/reducers/user';
import { removeAuth } from '@/utils/storage';
import { DatePicker, Dialog, List, Popup, Toast } from 'antd-mobile';
import dayjs from 'dayjs';
import { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useHistory } from 'react-router-dom';
import styles from './index.module.scss';

type EditType = 'photo' | 'gender' | 'intro' | 'name';
export default function ProfileEdit() {
  const dispatch = useDispatch();
  const history = useHistory();

  useEffect(() => {
    dispatch(getUserProfileAction());
  }, [dispatch]);

  const [editType, setEditType] = useState('' as EditType);
  const iptRef = useRef<HTMLInputElement>(null);

  const handleShowBottomPop = (editType: EditType) => {
    setVisible(true);
    setEditType(editType);
  };

  const handleChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const formData = new FormData();
    if (e.target.files) {
      formData.append('photo', e.target.files[0]);
    }
    await dispatch(updatePhotoAction(formData));
    Toast.show({ content: '更新成功' });
    setVisible(false);
  };

  const [visible, setVisible] = useState(false);
  const [rightVisible, setRightVisible] = useState(false);
  const [birthVisible, setBirthVisible] = useState(false);

  const { profile } = useAppSelector((state) => state.user);
  const [name, setName] = useState('');
  useEffect(() => {
    setName(profile.name);
  }, [profile.name]);

  const [intro, setIntro] = useState('');
  useEffect(() => {
    setIntro(profile.intro);
  }, [profile.intro]);

  const handleBack = () => {
    setRightVisible(false);
    if (editType === 'name') setName(profile.name);
    if (editType === 'intro') setIntro(profile.intro);
  };

  const hanleUpdateProfile = async (profile: Partial<ProfileType>) => {
    await dispatch(updateProfileAction(profile));
    Toast.show({ content: '更新成功' });
    setVisible(false);
    setRightVisible(false);
    setBirthVisible(false);
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') hanleUpdateProfile({ name });
  };

  const handleLoginOut = () => {
    Dialog.confirm({
      title: '温馨提示',
      content: '亲，您确定要退出吗？',
      onConfirm: () => {
        removeAuth();
        history.push('/login');
      },
    });
  };

  return (
    <div className={styles.root}>
      <div className="content">
        <NavBar>个人资料</NavBar>
        <div className="wrapper">
          <List className="profile-list">
            <List.Item
              arrow
              extra={<img className="avatar" src={profile.photo} alt="" />}
              onClick={() => handleShowBottomPop('photo')}
            >
              头像
            </List.Item>

            <List.Item
              arrow
              extra={profile.name}
              onClick={() => {
                setEditType('name');
                setRightVisible(true);
              }}
            >
              昵称
            </List.Item>

            <List.Item
              onClick={() => {
                setEditType('intro');
                setRightVisible(true);
              }}
              arrow
              extra={<span className="intro">{profile.intro}</span>}
            >
              简介
            </List.Item>

            <List.Item
              arrow
              extra={profile.gender === 0 ? '男' : '女'}
              onClick={() => handleShowBottomPop('gender')}
            >
              性别
            </List.Item>
            <List.Item
              arrow
              extra={profile.birthday}
              onClick={() => setBirthVisible(true)}
            >
              生日
            </List.Item>
          </List>

          <input
            onChange={(e) => handleChange(e)}
            ref={iptRef}
            className="avatar-upload"
            type="file"
          />
        </div>

        <div className="logout">
          <button className="btn" onClick={handleLoginOut}>
            退出登录
          </button>
        </div>
      </div>

      <DatePicker
        title="选择生日"
        visible={birthVisible}
        min={new Date('1900-01-01')}
        max={new Date()}
        value={new Date(profile.birthday)}
        onCancel={() => {
          setBirthVisible(false);
        }}
        onConfirm={(val) => {
          hanleUpdateProfile({ birthday: dayjs(val).format('YYYY-MM-DD') });
        }}
      ></DatePicker>
      <Popup
        position="bottom"
        bodyClassName="popup-bottom-list"
        visible={visible}
        onMaskClick={() => setVisible(false)}
      >
        {renderBottom()}
        <div className="list-item" onClick={() => setVisible(false)}>
          取消
        </div>
      </Popup>

      <Popup
        visible={rightVisible}
        onMaskClick={() => setRightVisible(false)}
        position="right"
        bodyClassName="popup-right"
        destroyOnClose
      >
        {renderRight()}
      </Popup>
    </div>
  );

  function renderBottom() {
    if (editType === 'photo') {
      return (
        <>
          <div className="list-item" onClick={() => iptRef.current?.click()}>
            拍照
          </div>
          <div className="list-item" onClick={() => iptRef.current?.click()}>
            本地选择
          </div>
        </>
      );
    }
    if (editType === 'gender') {
      return (
        <>
          <div
            className="list-item"
            onClick={() => hanleUpdateProfile({ gender: 0 })}
          >
            男
          </div>
          <div
            className="list-item"
            onClick={() => hanleUpdateProfile({ gender: 1 })}
          >
            女
          </div>
        </>
      );
    }
  }

  function renderRight() {
    let value = '';
    if (editType === 'name') value = name;
    if (editType === 'intro') value = intro;

    return (
      <>
        <NavBar
          onBack={handleBack}
          right={
            <span
              className="submit-btn"
              onClick={() => hanleUpdateProfile({ [editType]: value })}
            >
              提交
            </span>
          }
        >
          编辑
          {editType === 'intro' && '简介'}
          {editType === 'name' && '昵称'}
        </NavBar>
        <div className="edit-content">
          {editType === 'intro' && (
            <TextArea
              value={intro}
              onChange={(e) => setIntro(e.target.value)}
            />
          )}
          {editType === 'name' && (
            <Input
              onKeyDown={handleKeyDown}
              className="edit-input"
              autoFocus
              value={name}
              onChange={(e) => setName(e.target.value)}
            />
          )}
        </div>
      </>
    );
  }
}
